package cda;

import com.opencsv.CSVReader;

import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.io.IOException;
import java.util.*;

/**
　* @description: 根据输入内容，从检索模型匹配类似的字段
　* @author jzh
　* @date 2024/7/10 下午2:04
　*/
public class ScanModel {
    public static void main(String[] args) {
        String csvFile = "E:\\索引模型.csv";
        Map<String, String> map = new HashMap<>();

        try (CSVReader reader = new CSVReader(new InputStreamReader(new FileInputStream(csvFile), StandardCharsets.UTF_8))) {
            List<String[]> records = reader.readAll();

            String[] header = records.get(0);

            for (int i = 1; i < records.size(); i++) {
                String[] record = records.get(i);
                String key = record[0];
                String value = record[1];
                map.put(key, value);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8.name());

        while (true) {
            System.out.print("请输入键值 (输入 'q' 退出): ");
            String input = scanner.nextLine();
            if ("q".equalsIgnoreCase(input)) {
                break;
            }
//            String result = map.get(input);
            match(input, map);

//            if (result != null) {
//                System.out.println("结果: " + result);
//            } else {
//                System.out.println("键值不存在.");
//            }
        }

    }

    private static void match(String input, Map<String, String> map) {
        String table = null;
        List<String> bestMatch = new ArrayList<>();
        if (input.contains("#@#")){
            table = input.split("#@#")[1];
            input = input.split("#@#")[0];
        }

        System.out.println("======= 开始查找关键字：" + input + " ========");
        List<String> list = new ArrayList<>();
        for (String value : map.values()) {
            String field = value.substring(value.lastIndexOf("_") + 1);
            if (field.contains(input.trim())){
                list.add(value.replaceAll("_", "#"));
            }
        }
        list.sort(String::compareTo);
        list.forEach(System.out::println);
        System.out.println("==================================");

        if (table != null) {
            for (String s : list) {
                String tb = s.substring(0, s.indexOf("#") == -1 ? s.length() : s.indexOf("#"));
                if (tb.contains(table)) {
                    bestMatch.add(s);
                }
            }
        }
        bestMatch.forEach(System.out::println);
        System.out.println("==================================");

        System.out.println();
    }
}
